package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.vo.ExportFormDataVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.service.LogExportService;
import com.xbongbong.paas.service.PaasExcelService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.log.pojo.dto.LogExportDTO;
import com.xbongbong.pro.log.pojo.vo.LogExportVO;
import com.xbongbong.pro.paymenttask.pojo.dto.PaymentTaskExportDTO;
import com.xbongbong.pro.webexport.dto.CommunicatePlanExportDTO;
import com.xbongbong.pro.webexport.dto.CustomerStatementExportDTO;
import com.xbongbong.pro.webexport.dto.SignInExportDTO;
import com.xbongbong.pro.webexport.dto.WorkReportExportDTO;
import com.xbongbong.pro.weblist.pojo.dto.NearCustomerDTO;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Objects;

/**
 * 导入导出相关接口
 *
 * @author wufeng
 * @date 2018/9/21 10:57
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/file/excel")
public class PaasExcelExportController {

    @Resource
    private PaasExcelService paasExcelService;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private LogExportService logExportService;


    /**
     * 导出数据
     */
    @RequestMapping(value = "/export/form/data")
    public String exportFormData(@RequestBody @Valid FormDataListDTO formDataListDTO, BindingResult br, HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception {
        XbbResponse<ExportFormDataVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TransmittableThreadLocalUtil.setValue(formDataListDTO.getSaasMark(), formDataListDTO.getBusinessType(), formDataListDTO.getMenuId(), formDataListDTO.getDistributorMark());
                formDataListDTO.setFromExport(1);
                ExportFormDataVO exportFormDataVO = paasExcelService.exportFormData(formDataListDTO);
                response = new XbbResponse<>(exportFormDataVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
                String hashKey = formDataListDTO.getCorpid() + "_" + formDataListDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
                String hashKey = formDataListDTO.getCorpid() + "_" + formDataListDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.IgnoreNonFieldGetter);
    }


    /**
     * 导出附近客户
     */
    @RequestMapping(value = "/export/nearCustomer/form/data")
    public String exportNearCustomerFormData(@RequestBody @Valid NearCustomerDTO nearCustomerDTO, BindingResult br, HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception {
        XbbResponse<ExportFormDataVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TransmittableThreadLocalUtil.setValue(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), null, nearCustomerDTO.getDistributorMark());
                ExportFormDataVO exportFormDataVO = paasExcelService.exportNearCustomerFormData(nearCustomerDTO);
                response = new XbbResponse<>(exportFormDataVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
                String hashKey = nearCustomerDTO.getCorpid() + "_" + nearCustomerDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
                String hashKey = nearCustomerDTO.getCorpid() + "_" + nearCustomerDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.IgnoreNonFieldGetter);
    }


    /**
     * 导出访客计划
     */
    @RequestMapping(value = "/export/plan/form/data")
    public String exportCommunicatePlanData(@RequestBody @Valid CommunicatePlanExportDTO communicatePlanExportDTO, BindingResult br, HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception {
        XbbResponse<ExportFormDataVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TransmittableThreadLocalUtil.setValue(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.COMMUNICATE_PLAN.getCode(), null, communicatePlanExportDTO.getDistributorMark());
                ExportFormDataVO exportFormDataVO = paasExcelService.exportCommunicatePlanData(communicatePlanExportDTO);
                response = new XbbResponse<>(exportFormDataVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
                String hashKey = communicatePlanExportDTO.getCorpid() + "_" + communicatePlanExportDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
                String hashKey = communicatePlanExportDTO.getCorpid() + "_" + communicatePlanExportDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.IgnoreNonFieldGetter);
    }

    /**
     * 导出工作报告
     */
    @RequestMapping(value = "/export/work/report/data")
    public String exportWorkReportData(@RequestBody @Valid WorkReportExportDTO workReportExportDTO, BindingResult br, HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception {
        XbbResponse<ExportFormDataVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TransmittableThreadLocalUtil.setValue(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.WORK_REPORT.getCode(), null, workReportExportDTO.getDistributorMark());
                ExportFormDataVO exportFormDataVO = paasExcelService.exportWorkReportData(workReportExportDTO);
                response = new XbbResponse<>(exportFormDataVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
                String hashKey = workReportExportDTO.getCorpid() + "_" + workReportExportDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
                String hashKey = workReportExportDTO.getCorpid() + "_" + workReportExportDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.IgnoreNonFieldGetter);
    }

    /**
     * 导出签到
     */
    @RequestMapping(value = "/export/signIn/form/data")
    public String exportSignInData(@RequestBody @Valid SignInExportDTO signInExportDTO, BindingResult br, HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception {
        XbbResponse<ExportFormDataVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TransmittableThreadLocalUtil.setValue(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.SIGNIN.getCode(), null, signInExportDTO.getDistributorMark());
                ExportFormDataVO exportFormDataVO = paasExcelService.exportSignInData(signInExportDTO);
                response = new XbbResponse<>(exportFormDataVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
                String hashKey = signInExportDTO.getCorpid() + "_" + signInExportDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
                String hashKey = signInExportDTO.getCorpid() + "_" + signInExportDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.IgnoreNonFieldGetter);
    }

    /**
     * 导出对账单
     * @param customerStatementExportDTO
     * @param br
     * @param request
     * @param httpServletResponse
     * @return java.lang.String
     * @throws Exception
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    @RequestMapping(value = "/export/customerStatement/form/data", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String exportCustomerStatementData(@RequestBody @Valid CustomerStatementExportDTO customerStatementExportDTO, BindingResult br, HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception {
        XbbResponse<ExportFormDataVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TransmittableThreadLocalUtil.setValue(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.CUSTOMER_STATEMENT.getCode(), null, customerStatementExportDTO.getDistributorMark());
                ExportFormDataVO exportFormDataVO = paasExcelService.exportCustomerStatementData(customerStatementExportDTO);
                response = new XbbResponse<>(exportFormDataVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
                String hashKey = customerStatementExportDTO.getCorpid() + "_" + customerStatementExportDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
                String hashKey = customerStatementExportDTO.getCorpid() + "_" + customerStatementExportDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.IgnoreNonFieldGetter);
    }

    /**
     * Description: 导出工单列表
     * @param formDataListDTO
     * @param br
     * @return java.lang.String
     * @throws Exception
     * @author 刘阳
     * @date 2019/6/6 3:03 PM
     * @since v1.0
     */
    @RequestMapping(value = "/export/workOrder/form/data")
    public String exportWorkOrderData(@RequestBody @Valid FormDataListDTO formDataListDTO, BindingResult br) throws Exception {
        XbbResponse<ExportFormDataVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TransmittableThreadLocalUtil.setValue(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.WORK_ORDER.getCode(), null, formDataListDTO.getDistributorMark());
                formDataListDTO.setFromExport(1);
                ExportFormDataVO exportFormDataVO = paasExcelService.exportWorkOrderData(formDataListDTO);
                response = new XbbResponse<>(exportFormDataVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
                String hashKey = formDataListDTO.getCorpid() + "_" + formDataListDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            } catch (Exception unHandledException) {
                unHandledException.printStackTrace();
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
                String hashKey = formDataListDTO.getCorpid() + "_" + formDataListDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.IgnoreNonFieldGetter);
    }


    /**
     * 导出回款计划
     */
    @RequestMapping(value = "/export/paymentTask/form/data", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String exportPaymentTaskData(@RequestBody @Valid PaymentTaskExportDTO paymentTaskExportDTO, BindingResult br, HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception {
        XbbResponse<ExportFormDataVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TransmittableThreadLocalUtil.setValue(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.PAYMENT_TASK.getCode(), null, paymentTaskExportDTO.getDistributorMark());
                ExportFormDataVO exportFormDataVO = paasExcelService.exportPaymentTaskData(paymentTaskExportDTO);
                response = new XbbResponse<>(exportFormDataVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
                String hashKey = paymentTaskExportDTO.getCorpid() + "_" + paymentTaskExportDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
                String hashKey = paymentTaskExportDTO.getCorpid() + "_" + paymentTaskExportDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.IgnoreNonFieldGetter);
    }

    /**
     * 操作日志和登录日志导出
     */
    @RequestMapping(value = "/export/log",method = RequestMethod.POST)
    public String exportLog(@RequestBody @Valid LogExportDTO logExportDTO, BindingResult br) throws Exception {
        XbbResponse<LogExportVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                LogExportVO logExportVO = logExportService.exportLog(logExportDTO);
                response = new XbbResponse<>(logExportVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
                String hashKey = logExportDTO.getCorpid() + "_" + logExportDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
                String hashKey = logExportDTO.getCorpid() + "_" + logExportDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.IgnoreNonFieldGetter);
    }

}
